package com.itheima.em.util;

public class Utils {

    private static final double EARTH_RADIUS = 6371; // 地球半径（单位：公里）

    /**
     *计算 起始，到达 坐标点的直线距离
     * @param lon1 起始经度
     * @param lat1 起始维度
     * @param lon2 到达经度
     * @param lat2 到达维度
     * @return 单位公里数（千米）
     */
    public static double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        // 将经纬度转换为弧度
        double radLat1 = Math.toRadians(lat1);
        double radLon1 = Math.toRadians(lon1);
        double radLat2 = Math.toRadians(lat2);
        double radLon2 = Math.toRadians(lon2);

        // 使用球面三角法计算两点间的直线距离
        double a = Math.sin((radLat2 - radLat1) / 2) * Math.sin((radLat2 - radLat1) / 2)
                + Math.cos(radLat1) * Math.cos(radLat2) * Math.sin((radLon2 - radLon1) / 2) * Math.sin((radLon2 - radLon1) / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = EARTH_RADIUS * c;

        return distance;
    }
}
